package cn.liuche17.ibatis.plugins;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.Properties;

/**
 * @author：liuche
 * @Date：2024年11月03日 14:21
 * @Description：
 */
@Intercepts({ @Signature(type = StatementHandler.class,
  method = "prepare",
  args = { Connection.class, Integer.class}) })
public class MyPlugin implements Interceptor {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());
  // //这里是每次执行操作的时候，都会进行这个拦截器的方法内

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    //增强逻辑
    StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
    BoundSql boundSql = statementHandler.getBoundSql();
    String sql = boundSql.getSql();
    logger.info("mybatis intercept sql:{}", sql);
    return invocation.proceed(); //执行原方法
  }

  /**
   *
   * ^Description包装目标对象 为目标对象创建代理对象
   * @Param target为要拦截的对象
   * @Return代理对象
   */
  @Override
  public Object plugin(Object target) {
    System.out.println("将要包装的目标对象："+target);
    return Plugin.wrap(target,this);
  }

  /**获取配置文件的属性**/
  //插件初始化的时候调用，也只调用一次，插件配置的属性从这里设置进来
  @Override
  public void setProperties(Properties properties) {
    System.out.println("插件配置的初始化参数："+properties );
  }
}
